<?php
	


class PdoDriver extends LibBase{


	private $handle = null;
	
	/**
	 * 构造函数，初始化插件
	 */
	public function __construct($host,$user,$pwd,$dbname) {

		parent::__construct();
		$this->connect($host,$user,$pwd,$dbname);
	}
	
	

	
	public function connect($host,$user,$pwd,$dbname){
		try{	
			$this->handle = new PDO("mysql:host={$host};dbname={$dbname}",$user,$pwd);

		}catch(PDOException $e){
			echo $e->getMessage();
		}
		$this->handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		
	}
	public function reconnect(){
		
	}
	public function close(){
	
	}
	/**
	 * 执行一条sql，不返回结果
	 */
	public function exec($sql){
		try{
			$rs = $this->handle->exec($sql);
		}catch(PDOException $e){ 
			$this->errorlog($e->errorInfo);
		}
		return $rs;
	}


	/**
	 * 查询并返回2维数组
	 */
	public function select($sql,$resultType=PDO::FETCH_ASSOC){
		
		try{
			$execHandle = $this->handle->prepare($sql);
			$execHandle->execute();
			
			//记录最后一次sql，可能用于count方法
			$this->lastSql = $sql;
			$rs = $execHandle->fetchAll($resultType);
		}catch(PDOException $e){
			$this->errorlog($e->errorInfo);
		}
		return  $rs;
		
	}
	
	
	
	/**
	 * 提交事务
	 */
	public function commit(){
		$this->handle->commit();
	}
	
	/**
	 * 开始事务
	 */
	public function begin(){
		$this->handle->beginTransaction();
	}

	/**
	 * 回滚事务
	 */
	public function back(){
		$this->handle->rollBack();
	}	

	private function errorlog($error){
		$data['sqlstate_code'] = $error[0];
		$data['driver_code'] = $error[1];
		$data['message'] = $error[2];
		$data['event'] = N_EVENT;
		$data['action'] = N_ACTION;
		$data['ctime'] = time();
		$this->insert('db_sql_error_log',$data);
		throw new PException($error[2],999);
	}

}
